import {
  Component, computed, DestroyRef,
  inject,
  input, OnInit, signal
} from '@angular/core';

import {Task} from './task/task';
import {TasksService} from './tasks.service';
import {
  ActivatedRoute,
  RouterLink
} from '@angular/router';

@Component({
  selector: 'app-tasks',
  imports: [
    Task,
    RouterLink
  ],
  templateUrl: './tasks.html',
  styleUrl: './tasks.css'
})
export class Tasks implements OnInit{
  userId = input.required<string>();

  // order = input<'asc' | 'desc'>();

  order = signal<'asc' | 'desc'>('desc');

  private activatedRoute = inject(ActivatedRoute);

  private tasksService = inject(TasksService);
  private destroyRef = inject(DestroyRef);

  userTasks=computed(()=>
    this.tasksService.allTasks().filter((task)=>task.userId === this.userId())
      .sort((a,b)=> {
      if(this.order()==='desc'){
        return a.id > b.id ? -1 : 1;
      }else{
        return a.id > b.id ? 1 : -1;
      }
    })
  );


  ngOnInit():void{
  const subscription =  this.activatedRoute.queryParams.subscribe({
      next:params => (this.order.set(params['order']))
    });

  this.destroyRef.onDestroy(()=> subscription.unsubscribe());
  }



}
